package com.chao.deeply.aqs;

/**
 * @author : Rookie
 * @description : 三个线程循环打印1-100
 * @date : 2023/8/28
 */
public class PrintThread2 {

    private static int THREAD_COUNT = 3;
    private static int START = 1;
    private static int END = 100;
    private static int currThreadId = 1;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintThread(1));
        Thread t2 = new Thread(new PrintThread(2));
        Thread t3 = new Thread(new PrintThread(3));

        t1.start();
        t2.start();
        t3.start();
    }

    private static class PrintThread implements Runnable {
        private final int threadId;

        PrintThread(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while (START <= END) {
                synchronized (lock) {
                    while (currThreadId != threadId) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (START <= END) {
                        System.out.println("线程" + currThreadId + "打印了" + START);
                        START++;
                    }
                    currThreadId = (threadId%THREAD_COUNT)+1;
                    lock.notifyAll();
                }
            }
        }
    }
 }
